package demo.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * 通用工具类
 * 
 * @author hanjy
 *
 */
public class CommonUtil {

    private CommonUtil() {
        super();
    }

    static Random random = new Random();

    private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    /**
     * 判断两个List是否相等
     * 
     * @param src
     * @param tar
     * @return
     */
    public static boolean equals(List<Object[]> src, List<Object[]> tar) {
        if (src == tar) {
            return true;
        }

        if (src == null || tar == null) {
            return false;
        }

        if (src.size() != tar.size()) {
            return false;
        }
        for (int i = 0; i < src.size(); i++) {
            if (!Arrays.equals(src.get(i), tar.get(i))) {
                logger.warn("src:{},tar:{}", JSONObject.toJSONString(src.get(i)), JSONObject.toJSONString(tar.get(i)));
                return false;
            }
        }
        return true;
    }

    /**
     * 对象转json String
     * 
     * @param o
     * @return
     */
    public static String transfer(Object o) {
        if (o == null) {
            return "null";
        }
        if (o instanceof String || o instanceof Number || o instanceof LocalDateTime || o instanceof LocalDate
                || o instanceof LocalTime) {
            return o.toString();
        }
        return JSONObject.toJSONString(o);
    }

    /**
     * 将MAP VALUE的OBJECT 类型转String类型
     * 
     * @param map
     * @return
     */
    public static Map<String, String> transferMap(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return Collections.emptyMap();
        }
        return map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, t -> transfer(t.getValue())));
    }

    /**
     * 将 {app=ad-web,ioType=read,instance=aa}类型的字符串转map
     * 
     * @param str
     * @return
     */
    public static Map<String, String> transferMap(String str) {
        if (str == null || str.isEmpty()) {
            return Collections.emptyMap();
        }
        if (str.startsWith("{")) {
            str = str.substring(1);
        }
        if (str.endsWith("}")) {
            str = str.substring(0, str.length() - 1);
        }
        return Stream.of(str.split(",")).map(s -> s.split("="))
                .collect(Collectors.toMap(a -> a[0].trim(), a -> a[1].trim()));
    }

}
